package com.github.number;

import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * @author zhangcheng
 * @date 2022/7/31 22:35
 * @description
 */
public class NumberUtil {

    public static void main(String[] args) {
        ////方法1
        double dd = Math.round(0.1256 * 100) / 100.0;
        System.out.println("方法1=" + dd);
        // (double) (Math.round(sd3*10000)/10000.0);   这样为保持4位

        ////方法2
        DecimalFormat df2 = new DecimalFormat("###.00");
        DecimalFormat df3 = new DecimalFormat("##0.000");

        System.out.println("方法2=" + df2.format(0.1256));
        System.out.println("方法2=" + df3.format(1.1256));

        ////方法3
//        String ss = String.format("%10.2f%%", 1.1256);  //1.13f
//        String ss = String.format("%10.2f", 1.1256);   //       1.13
        String ss = String.format("%.3f", 1.1256);   //1.13
        System.out.println("方法3=" + ss);

        ////方法4
        double x = 0.142;
        NumberFormat ddf1 = NumberFormat.getNumberInstance();// 线程不安全
        ddf1.setMaximumFractionDigits(2);
        String s = ddf1.format(x);
        System.out.println("方法4=" + s);   //四舍五入   23.55

        ////方法5
//        float T = 0.1257f;
//        BigDecimal b = new BigDecimal(T);
//        T = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
//        System.out.println("方法5：" + T);
    }


}
